import { View } from "@tarojs/components";
import { AtForm, AtInput, AtButton, AtMessage, AtSwitch } from "taro-ui";
import { useState } from "react";
import Taro, { useRouter, useDidShow } from "@tarojs/taro";
import { getPointDetailApi, changePointApi } from "../../utils/api";

import "./index.scss";

const Index = () => {
  const id = useRouter().params.id;

  const [name, set_name] = useState("");
  const [tag, set_tag] = useState("");
  const [state, set_state] = useState("");

  useDidShow(async () => {
    const res = await getPointDetailApi({
      point_id: id
    });
    if (res.res === 0) {
      set_name(res.record.name);
      set_tag(res.record.tag);
      set_state(res.record.state);
    } else {
      Taro.atMessage({
        message: res.msg,
        type: "warning"
      });
    }
  });

  const nameChange = value => {
    set_name(value);
  };

  const tagChange = value => {
    set_tag(value);
  };

  const statechange = value => {
    set_state(value ? "2" : "1");
  };

  const onSubmit = async () => {
    const res = await changePointApi({
      point_id: id,
      name,
      tag,
      state
    });
    if (res.res === 0) {
      Taro.atMessage({
        message: "修改成功",
        type: "success"
      });
      Taro.navigateBack({
        delta: 1
      });
    } else {
      Taro.atMessage({
        message: res.msg,
        type: "warning"
      });
    }
  };

  return (
    <View className="batchadd">
      <AtForm>
        <AtInput
          name="name"
          title="布点名称"
          type="text"
          placeholder="请输入布点名称"
          value={name}
          onChange={nameChange}
        />

        <AtInput
          name="tag"
          title="布点标签"
          type="text"
          placeholder="请输入布点标签"
          value={tag}
          onChange={tagChange}
        />

        {/* <AtSwitch
          title={"布点状态(" + (state == "2" ? "开启中" : "已停用") + ")"}
          checked={state == "2"}
          onChange={statechange}
        /> */}

        <AtButton type="primary" onClick={onSubmit}>
          提交
        </AtButton>
      </AtForm>
      <AtMessage />
    </View>
  );
};

export default Index;
